# -*- coding: utf-8 -*-

"""
@author: david
@software: PyCharm
@file: encode.py
@time: 2021/12/1 17:14
@desc:
"""

import base64
from Crypto.Cipher import AES
import urllib.parse
import time  # 引入time模块

'''
采用AES对称加密算法
'''


# str不是32的倍数那就补足为16的倍数
def add_to_32(value):
    while len(value) % 32 != 0:
        value += '\0'
    return str.encode(value)  # 返回bytes


def add_to_16(value):
    while len(value) % 16 != 0:
        value += '\0'
    return str.encode(value)  # 返回bytes


# 加密方法
def encrypt_oracle(text):
    # 秘钥
    key = 'WyX0tNukn5gw2awX'
    # 待加密文本
    # 初始化加密器
    aes = AES.new(add_to_16(key), AES.MODE_ECB)
    # 先进行aes加密
    encrypt_aes = aes.encrypt(add_to_16(text))
    # 用base64转成字符串形式
    # base = base64.encodebytes(encrypt_aes)
    # base = base64.b64encode(encrypt_aes)
    # print(base)
    encrypted_text = str(base64.b64encode(encrypt_aes), encoding='utf-8')  # 执行加密并转码返回bytes
    # print(encrypted_text)
    return encrypted_text


# 解密方法
def decrypt_oralce(text):
    # 秘钥
    key = 'WyX0tNukn5gw2awX'
    # 密文
    # 初始化加密器
    aes = AES.new(add_to_16(key), AES.MODE_ECB)
    # 优先逆向解密base64成bytes
    base64_decrypted = base64.decodebytes(text.encode(encoding='utf-8'))
    # 执行解密密并转码返回str
    decrypted_text = str(aes.decrypt(base64_decrypted), encoding='utf-8').replace('\0', '')
    # print('decrypted_text', decrypted_text)
    return decrypted_text


if __name__ == '__main__':
    cpuid = '94c078f3c51034110a11'
    mac_lan = 'f8:9f:b8:ce:60:6e'
    mac_wlan = '70:4a:0e:58:75:9c'
    batch_no = time.strftime("%Y%m%d", time.localtime())  # 当前日期
    text = 'PRODUCT_ID:MK-3\nCPUID:' + cpuid + '\nMAC_LAN:' + mac_lan + '\nMAC_WLAN:'+mac_wlan+'\nAPP_ID:1000\nBATCH_NO:' + batch_no
    entrypted_text = encrypt_oracle(text)
    print('加密：', entrypted_text)
    print('解密：', decrypt_oralce(entrypted_text))
    entrypted_text = urllib.parse.quote(entrypted_text)  # urlencode编码
    print('urlencode编码：', entrypted_text)

    url = 'https://qrcode-h5.jsunet.cn/app/default?k=' + entrypted_text + '&appId=1000&SN=' + cpuid + '&productId=MK-3'
    print('url: ', url)
